<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useColumns } from "./columns";
import router from "@/router";
// import { Experiment, getRunningExperiments } from "@/api/LabExperimentApi";
import { setDefaultPlatform } from "@/api/LabPlatformApi";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import dialogForm from "./components/DialogForm.vue";
import { ElMessageBox } from "element-plus";

const tableRef = ref();

const {
  loading,
  columns,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  onCurrentChange
} = useColumns();

const props = defineProps({
  configData: {
    type: Object
  },
  labPlatformData: {
    type: Array
  },
  newPagination: {
    type: Object as () => PaginationProps
  },
  platformID: {
    type: String
  },
  isRuning: {
    type: Boolean
  }
});

const currentPlatformID = ref(props.platformID);
const currentPlatformData = ref({});
// const disabled = ref(false);

onMounted(async () => {
  // const res = await getRunningExperiments();
  // if (!res.errorCode) {
  //   if (res.data) {
  //     disabled.value = true;
  //   }
  //   console.log(res);
  // } else {
  //   message(`${res.message}`, { type: "error" });
  // }
});

const emit = defineEmits(["delete-item"]);

//删除实验
const handleClickDelete = async expID => {
  emit("delete-item", expID);
};
const formDialogVisible = ref(false);

//跳转实验配置监控
const clickNew = row => {
  localStorage.setItem(
    "defaultMonitorQuery",
    JSON.stringify({ configId: row.id, configFlag: 1 })
  );

  router.push({
    name: "Monitor",
    query: { configId: row.id, configFlag: 1 }
  });
};

//创建新实验
const addNewExp = row => {
  formDialogVisible.value = true;
  currentPlatformID.value = row.id;
  currentPlatformData.value = row;
};

const clickSetDefalut = row => {
  ElMessageBox.confirm(`确定将${row.name}设为默认实验`, "提示", {
    type: "warning"
  })
    .then(async () => {
      const ret = await setDefaultPlatform(row.id);
      if (!ret.errorCode) {
        //修改configData里面的isDefault
        for (const item in props.configData) {
          if (props.configData[item].id === row.id) {
            props.configData[item].isDefault = true;
          } else {
            props.configData[item].isDefault = false;
          }
        }
        message("设置成功", { type: "success" });
      } else {
        message(`设置失败，${ret.message}`, { type: "error" });
      }
    })
    .catch(() => {});
};

// const deleteExp = row => {
//   ElMessageBox.confirm(
//     `确认删除后${row.name}的所有设备信息将被清空, 且无法恢复`,
//     "提示",
//     { type: "warning" }
//   )
//     .then(async () => {
//       const res = await deleteDevice({ deviceId: device.id });

//       if (res.errorCode === 0) {
//         message("删除成功", { type: "success" });
//         configData.value = configData.value.filter(item => {
//           return item.deviceId != row.deviceId;
//         });
//         fetchData(); // 重新获取设备列表
//       } else {
//         message(res.message, { type: "error" }); // 显示错误消息
//       }
//     })
//     .catch(() => {});
// };

// watch(
//   () => props.configData,
//   newVal => {
//     for (const item in newVal) {
//       const exist = JSON.parse(
//         localStorage.getItem(`settingList${newVal[item].id}`)
//       );
//       if (exist && exist.value) {
//         continue;
//       }
//       localStorage.removeItem(`settingList${newVal[item].id}`);
//     }
//   }
// );

// function handleClick(row) {
//   console.log(
//     "%crow===>>>: ",
//     "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
//     row
//   );
// }
</script>

<template>
  <pure-table
    ref="tableRef"
    border
    adaptive
    :adaptiveConfig="adaptiveConfig"
    row-key="id"
    alignWhole="center"
    showOverflowTooltip
    :loading="loading"
    :loading-config="loadingConfig"
    :data="configData"
    :columns="columns"
    :pagination="newPagination"
    @page-size-change="onSizeChange"
    @page-current-change="onCurrentChange"
  >
    <template #name="{ row }">
      <el-tag type="info" v-if="row.isDefault"> {{ row.name }}</el-tag>
      <el-text type="info" size="small" v-else>{{ row.name }}</el-text>
    </template>
    <template #duration="{ row }">
      {{ row.days ? row.days + "天" : ""
      }}{{ row.hours ? row.hours + "小时" : ""
      }}{{ row.minutes ? row.minutes + "分钟" : ""
      }}{{ row.seconds ? row.seconds + "秒" : "" }}
    </template>
    <template #expPlatformId="{ row }">
      {{
        row.parentId
          ? labPlatformData.find(obj => {
              return obj.id === row.parentId;
            }).name
          : labPlatformData.find(obj => {
              return obj.id === platformID;
            }).name
      }}
    </template>
    <template #operation="{ row }">
      <el-button
        link
        type="primary"
        :disabled="isRuning"
        size="small"
        @click="clickNew(row)"
      >
        配置
      </el-button>
      <el-button
        link
        type="primary"
        size="small"
        :disabled="row.isDefault ? true : false"
        @click="clickSetDefalut(row)"
        >设为默认</el-button
      >
      <el-button
        :disabled="isRuning ? true : row.ext == '' ? true : false"
        link
        type="primary"
        size="small"
        @click="addNewExp(row)"
        >创建新实验</el-button
      >
      <el-button
        :disabled="isRuning"
        link
        type="primary"
        size="small"
        @click="handleClickDelete(row.id)"
        >删除</el-button
      >
    </template>
  </pure-table>
  <dialogForm
    :data="currentPlatformData"
    v-model:visible="formDialogVisible"
    :platformID="currentPlatformID"
  />
</template>
